package shop_cart

import (
	"context"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"
	"strconv"
	"web/order/api"
	"web/order/forms"
	"web/order/global"
	"web/order/proto"
)

// 向用户的购物车中添加商品
func AddGoods(ctx *gin.Context) {
	f := new(forms.ShopCartItemForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	var userId int32
	if val, ok := ctx.Get("userId"); ok {
		userId = val.(int32)
	} else {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"msg": "请重新登录",
		})
		return
	}

	if _, err := global.OrderSrvClient.CreateCartItem(context.Background(), &proto.CartItemRequest{
		UserId:  userId,
		GoodsId: f.GoodsId,
		Nums:    f.Nums,
	}); err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "购物车中添加商品成功",
	})
}

// 查看购物车记录
func GetShopCartRecords(ctx *gin.Context) {
	var userId int32
	if val, ok := ctx.Get("userId"); ok {
		userId = val.(int32)
	} else {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"msg": "请重新登录",
		})
		return
	}

	res, err := global.OrderSrvClient.CartItemList(context.Background(), &proto.UserInfo{
		Id: userId,
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	var g []gin.H
	for _, v := range res.Data {
		g = append(g, gin.H{
			"id":       v.Id,
			"user_id":  v.UserId,
			"goods_id": v.GoodsId,
			"nums":     v.Nums,
			"checked":  v.Checked,
		})
	}

	ctx.JSON(http.StatusOK, gin.H{
		"total": res.Total,
		"data":  g,
	})
}

// 更新购物车中的记录
func UpdateCartItem(ctx *gin.Context) {
	var userId int32
	if val, ok := ctx.Get("userId"); ok {
		userId = val.(int32)
	} else {
		ctx.JSON(http.StatusUnauthorized, gin.H{
			"msg": "请重新登录",
		})
		return
	}

	idStr := ctx.Param("goodId")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：", err)
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": "解析参数出错，请检查商品id参数",
		})
		return
	}

	f := new(forms.ShopCartItemUpdateForm)
	if err := ctx.ShouldBind(&f); err != nil {
		api.HandleValidatorError(ctx, err)
		return
	}

	if _, err := global.OrderSrvClient.UpdateCartItem(context.Background(), &proto.CartItemRequest{
		Id:      userId,
		GoodsId: int32(idInt),
		Nums:    f.Nums,
	}); err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"msg": "更新成功",
	})
}

// 删除购物车中的一条记录
func DeleteCartItem(ctx *gin.Context) {
	// 这里获取到的cartId是shopping_cart表的主键id
	idStr := ctx.Param("cartId")
	idInt, err := strconv.Atoi(idStr)
	if err != nil {
		zap.S().Error("strconv.Atoi：string转int类型发生错误")
		ctx.JSON(http.StatusNotFound, gin.H{
			"msg": "解析参数出错，请检查购物车主键id参数",
		})
		return
	}

	_, err = global.OrderSrvClient.DeleteCartItem(context.Background(), &proto.CartItemRequest{
		Id: int32(idInt),
	})
	if err != nil {
		api.HandleGrpcErrorToHttp(err, ctx)
		return
	}
	ctx.JSON(http.StatusOK, gin.H{
		"msg": "删除成功",
	})
}
